﻿//************************************************************************
//Developed by Guo Ming Li 2009/2010
//Source code:
//  The source code may be freely modified or used but this credit section may not be removed 
//  The original author must be notified of any modifications plus a copy of 
//  the changed source code
//Contact info: mailto://gming.li@gmail.com
//************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Xml;
using GML.BizTalk.OperationManager.Library;
using GML.BizTalk.OperationManager.MSBTSOperations;
using System.Collections;
using System.Windows.Threading;


namespace GML.BizTalk.OperationManager.MSBTSOperationsWPF
{
    //public class TextRelay
    //{
    //    string _Text = null;
    //    public string Text { 
    //        set{
    //            this._Text = value;
    //        } 
    //        get{
    //            return this._Text;
    //        }

    //    }
    //}

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Microsoft.Win32.OpenFileDialog openFileDialog1;
        private GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations oOps = null;
        private GML.BizTalk.OperationManager.MSBTSOperations.Environment[] envInfos = null;
        private delegate void SimpleDelegate();

        private readonly Color DEFAULT_COLOR = Colors.Gray;
        private readonly double HEADER_FONT_SIZE = 12.0;
        private int previousContentLength = 0;
        private int _TotalOperationCount = 0;
        private int _FailedOperationCount = 0;
        private int _SuccessfulOperationCount = 0;
        private int _SkippedOperationCount = 0;
        private enum TextType
        {
            HEADER,
            BODY
        }

        public MainWindow()
        {
            InitializeComponent();

            Logger.Configure();

            this.openFileDialog1 = new Microsoft.Win32.OpenFileDialog();
            this.openFileDialog1.FileName = "";
            this.openFileDialog1.InitialDirectory = ".";
            this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOK);
        }

        private void openFileDialog1_FileOK(object sender, CancelEventArgs e)
        {
            this.tb_fileName.Text = this.openFileDialog1.FileName.ToString();
            this.btnPerformAction.IsEnabled = true;
            XmlDocument oDoc = new XmlDocument();
            string sXmlFileName = this.tb_fileName.Text.Trim();
            List<ComboBoxItem> ds = new List<ComboBoxItem>();

            try
            {
                LogHelper(GetFormattedHeader("Deployment Configuration XML"), Logger.ServerityLevel.INFO, TextType.HEADER);
                LogHelper(sXmlFileName, Logger.ServerityLevel.INFO, TextType.BODY);

                oDoc.Load(sXmlFileName);

                oOps = (GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations)GML.Common.Utilities.Xml.Deserialize2Object(oDoc.InnerXml.Trim(), typeof(GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations));

                envInfos = oOps.EnvironmentInfo;

                if (envInfos != null)
                {
                    foreach (GML.BizTalk.OperationManager.MSBTSOperations.Environment env in envInfos)
                    {
                        ds.Add(new ComboBoxItem
                        {
                            Content = env.EnvID
                        });
                    }
                }
                else
                {
                    //ds.Add("Default");
                    ds.Add(new ComboBoxItem
                    {
                        Content = "Default"
                    });

                }

                this.cbEnvInfo.ItemsSource = ds;
                this.cbEnvInfo.IsEnabled = true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                oDoc = null;
                sXmlFileName = null;
                ds = null;
            }
        }

        private void btn_openFile_Click(object sender, RoutedEventArgs e)
        {
            this.openFileDialog1.ShowDialog();
        }

        private BtsServer[] GetBtsServerForEnvironment(GML.BizTalk.OperationManager.MSBTSOperations.Environment[] envInfos, string sEnvID)
        {
            foreach (GML.BizTalk.OperationManager.MSBTSOperations.Environment env in this.envInfos)
            {
                if (env.EnvID == sEnvID)
                {
                    return env.BtsServers;
                }
            }
            return null;
        }

        private static int CountStringOccurrences(string text, string pattern)
        {
            // Loop through all instances of the string 'text'.
            int count = 0;
            int i = 0;
            while ((i = text.IndexOf(pattern, i)) != -1)
            {
                i += pattern.Length;
                count++;
            }
            return count;
        }

        private void LogHelper(string message, Logger.ServerityLevel serverity, TextType textType)
        {
            SimpleDelegate myDelegate = delegate()
            {
                try
                {

                    string newMessage = message + System.Environment.NewLine;
                    int lengthOfNLChars = CountStringOccurrences(newMessage, System.Environment.NewLine) * System.Environment.NewLine.Length;
                    System.Diagnostics.Debug.WriteLine("newMessage has " + lengthOfNLChars + " NewLine");
                    this.tbProgress.AppendText(newMessage);

                    TextPointer text = this.tbProgress.Document.ContentStart;
                    while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
                    {
                        text = text.GetNextContextPosition(LogicalDirection.Forward);
                    }

                    TextPointer startPos = text.GetPositionAtOffset(previousContentLength);
                    TextPointer endPos = text.GetPositionAtOffset(previousContentLength + newMessage.Length);

                    previousContentLength += newMessage.Length + lengthOfNLChars;

                    var textRange = new TextRange(startPos, endPos);
                    if (serverity.Equals(Logger.ServerityLevel.DEBUG) || serverity.Equals(Logger.ServerityLevel.INFO))
                    {
                        textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(DEFAULT_COLOR));
                    }
                    else if (serverity.Equals(Logger.ServerityLevel.ERROR))
                    {
                        textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                        if(!textType.Equals(TextType.HEADER)) textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                    }
                    else if (serverity.Equals(Logger.ServerityLevel.FATAL))
                    {
                        textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                        textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
                        if (!textType.Equals(TextType.HEADER)) textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                    }
                    else //if (serverity.Equals(Logger.ServerityLevel.WARN))
                    {
                        textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.PaleVioletRed));
                    }

                    if (textType.Equals(TextType.HEADER))
                    {
                        textRange.ApplyPropertyValue(TextElement.FontSizeProperty, HEADER_FONT_SIZE);
                    }

                }
                catch (Exception e)
                {                    
                    System.Diagnostics.Debug.WriteLine(e.Message + System.Environment.NewLine + e.StackTrace);
                } 
                Logger.doLog(Guid.NewGuid().ToString(), message, serverity);
            };
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, myDelegate);
        }

        private string GetFormattedHeader(string headerText)
        {
            return 
                "============================================================================" + System.Environment.NewLine +
                "|| " + headerText +  System.Environment.NewLine +
                "============================================================================" + System.Environment.NewLine ;
        }

        private void PerformAction_ReceiveLocations(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocations receiveLocations = null;
            ReceiveLocation receiveLocation = null;
            bool blnOperationSuccessful = false;
            try
            {
                receiveLocations = (GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocations)op.Item;
                foreach (ReceiveLocation _receiveLocation in receiveLocations.ReceiveLocation)
                {
                    if (_receiveLocation.EnvID.Equals(sEnvID))
                    {
                        receiveLocation = _receiveLocation;
                        break;
                    }
                }

                LogHelper(
                    GetFormattedHeader("Found operation [" + op.ExecSequence + "] type [" + receiveLocation.Action.ToString() + " receive location(s)]"),
                    Logger.ServerityLevel.INFO, TextType.HEADER
                    );
                try
                {
                    if (receiveLocation.ReceiveLocationProperties == null
                        && receiveLocation.ReceivePortName == null
                        && receiveLocation.Action.Equals(ReceiveLocationActionType.ENABLE_ALL))
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.ReceiveLocations.EnableAllReceiveLocation(
                            dbServerName,
                            mgntDbName,
                            receiveLocation.ApplicatonName,
                            out outException);
                    }
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }

                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                receiveLocations = null;
                receiveLocation = null;
            }
        }

        private void PerformAction_SendPorts(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.SendPorts sendPorts = null;
            SendPort sendPort = null;
            try
            {
                bool blnOperationSuccessful = false;
                sendPorts = (GML.BizTalk.OperationManager.MSBTSOperations.SendPorts)op.Item;
                foreach (SendPort _sendPort in sendPorts.SendPort)
                {
                    if (_sendPort.EnvID.Equals(sEnvID))
                    {
                        sendPort = _sendPort;
                        break;
                    }
                }

                LogHelper(
                    GetFormattedHeader("Found operation [" + op.ExecSequence + "] type [" + sendPort.Action.ToString() + " send port(s)]"),
                    Logger.ServerityLevel.INFO, TextType.HEADER
                    );
                try
                {
                    if (sendPort.SendPortProperties == null && sendPort.Action.Equals(SendPortActionType.START_ALL))
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.SendPorts.StartAllSendPorts(
                            dbServerName,
                            mgntDbName,
                            sendPort.ApplicatonName,
                            out outException);
                    }
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }

                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                sendPorts = null;
                sendPort = null;
            }
        }
        private void PerformAction_SendPortGroups(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroups sendPortGroups = null;
            SendPortGroup sendPortGroup = null;
            try
            {
                bool blnOperationSuccessful = false;
                sendPortGroups = (GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroups)op.Item;
                foreach (SendPortGroup _sendPortGroup in sendPortGroups.SendPortGroup)
                {
                    if (_sendPortGroup.EnvID.Equals(sEnvID))
                    {
                        sendPortGroup = _sendPortGroup;
                        break;
                    }
                }

                LogHelper(
                    GetFormattedHeader("Found operation [" + op.ExecSequence + "] type [" + sendPortGroup.Action.ToString() + " send port Group(s)]"),
                    Logger.ServerityLevel.INFO, TextType.HEADER
                    );
                try
                {
                    if (sendPortGroup.SendPortGroupProperties == null && sendPortGroup.Action.Equals(SendPortGroupActionType.START_ALL))
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.SendPortGroups.StartAllSendPortGroups(
                            dbServerName,
                            mgntDbName,
                            sendPortGroup.ApplicatonName,
                            out outException);
                    }
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }

                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                sendPortGroups = null;
                sendPortGroup = null;
            }
        }

        private void PerformAction_HostInstances(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.HostInstances hostInstances = (GML.BizTalk.OperationManager.MSBTSOperations.HostInstances)op.Item;
            HostInstance hostInstance = null;
            try
            {
                bool blnOperationSuccessful = false;
                hostInstances = (GML.BizTalk.OperationManager.MSBTSOperations.HostInstances)op.Item;
                foreach (HostInstance _hostInstance in hostInstances.HostInstance)
                {
                    if (_hostInstance.EnvID.Equals(sEnvID))
                    {
                        hostInstance = _hostInstance;
                        break;
                    }
                }

                LogHelper(
                    GetFormattedHeader("Found operation [" + op.ExecSequence + "] type [" + hostInstance.Action.ToString() + " host instance(s)]"),
                    Logger.ServerityLevel.INFO, TextType.HEADER
                    );
                try
                {
                    if (hostInstance.HostInstanceProperties == null && hostInstance.Action.Equals(HostInstanceActionType.START_ALL))
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.HostInstances.StartAllHostInstances(out outException);
                    }
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }

                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                hostInstances = null;
                hostInstance = null;
            }
        }

        private void PerformAction_ServiceInstances(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstances serviceInstances = (GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstances)op.Item;
            ServiceInstance serviceInstance = null;
            bool blnOperationSuccessful = false;
            try
            {
                serviceInstances = (GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstances)op.Item;
                foreach (ServiceInstance _serviceInstance in serviceInstances.ServiceInstance)
                {
                    if (_serviceInstance.EnvID.Equals(sEnvID))
                    {
                        serviceInstance = _serviceInstance;
                        break;
                    }
                }

                LogHelper(
                    GetFormattedHeader("Found operation [" + op.ExecSequence + "] type [" + serviceInstance.Action.ToString() + " service instance(s)]"),
                    Logger.ServerityLevel.INFO, TextType.HEADER
                    );
                try
                {
                    if (serviceInstance.ServiceTypes == null && serviceInstance.Action.Equals(ServiceInstanceActionType.RESUME_ALL_ADMIN_SUSPENDED))
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.ServiceInstances.StartAllAdminSuspendedInstances(
                                                dbServerName,
                                                mgntDbName,
                                                out outException);
                    }
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }

                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                serviceInstances = null;
                serviceInstance = null;
            }
        }
       
        private void PerformAction_GACListCompare(Operation op, GML.BizTalk.OperationManager.MSBTSOperations.Environment[] envInfos, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            Hashtable gacLists = new Hashtable();
            GACList gacList = null;
            GACVerification gacVerification = null;
            GACEntry[] gacEntries = null;
            BtsServer[] btsServers = null;
            List<GACEntry> missingGacEntries = null;
            bool blnOperationSuccessful = false;

            try
            {
                LogHelper(
                    GetFormattedHeader("Found operation [" + op.ExecSequence + "] type [" + GML.BizTalk.OperationManager.Library.OperationsType.GACVerification.ToString() + "]"),
                    Logger.ServerityLevel.INFO, TextType.HEADER
                    );


                gacVerification = (GACVerification)op.Item;
                gacEntries = gacVerification.Assemblies;
                btsServers = this.GetBtsServerForEnvironment(envInfos, sEnvID);

                //get the list of assembly from GAC on each computer
                foreach (BtsServer btsServer in btsServers)
                {
                    gacList = new GACList();
                    missingGacEntries = new List<GACEntry>();
                    string machineName = btsServer.ComputerName;
                    string filter = gacVerification.GACListFilter;

                    if (GML.BizTalk.OperationManager.Library.NetTools.IsValidMachineName(machineName))
                    {
                        gacList.LoadList(machineName, filter + "*");
                        missingGacEntries = gacList.GetMissingEntry(gacEntries, gacVerification.VerificationFilter);
                        if (missingGacEntries.Count > 0)
                        {
                            blnOperationSuccessful = false;
                            LogHelper(machineName + " is missing the following Assemblies in GAC.", Logger.ServerityLevel.ERROR, TextType.BODY);
                            foreach (GACEntry ge in missingGacEntries)
                            {
                                LogHelper(ge.ToString(gacVerification.VerificationFilter), Logger.ServerityLevel.ERROR, TextType.BODY);
                            }
                        }
                        else
                        {
                            blnOperationSuccessful = true;
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                blnOperationSuccessful = false;
                outException = ex;
            }
            finally
            {
                outException = null;
            }
            LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
            if (!blnOperationSuccessful && outException != null)
            {
                LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
            }
            if (!blnOperationSuccessful)
            {
                _FailedOperationCount++;
            }
            else
            {
                _SuccessfulOperationCount++;
            }
        }

        private void PerformAction_BindingInfo(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            BindingInfoCollection bindingInfoCollection = null;
            bool blnOperationSuccessful = false;
            try
            {
                bindingInfoCollection = (BindingInfoCollection)op.Item;
                foreach (BindingInfo bindingInfo in bindingInfoCollection.BindingInfo)
                {
                    LogHelper(GetFormattedHeader("Found operation [" + op.ExecSequence + "] type : " + bindingInfo.GetType().Name + ".Import"), Logger.ServerityLevel.INFO, TextType.BODY);
                    try
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.BtsBindingInfo.Import
                    (new Nullable<bool>(true),
                    dbServerName,
                    mgntDbName,
                    bindingInfo.ApplicationName,
                    bindingInfo.FileSource);

                    }
                    catch (Exception exception)
                    {
                        blnOperationSuccessful = false;
                        outException = exception;
                    }
                    LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                    if (!blnOperationSuccessful && outException != null)
                    {
                        LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                        LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                    }
                    if (!blnOperationSuccessful)
                    {
                        _FailedOperationCount++;

                    }
                    else
                    {
                        _SuccessfulOperationCount++;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                bindingInfoCollection = null;
            }
        }

        private void PerformAction_OrphanOrchestrationManagement(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.OrphanOrchestrationManagement osm = null;
            Orchestration[] orchs = null;
            try
            {
                bool blnOperationSuccessful = false;
                osm = (GML.BizTalk.OperationManager.MSBTSOperations.OrphanOrchestrationManagement)op.Item;
                orchs = osm.RemovalExclusions;
                LogHelper(GetFormattedHeader("Found operation [" + op.ExecSequence + "] type : " + osm.GetType().Name + ".Removal"), Logger.ServerityLevel.INFO, TextType.HEADER);
                try
                {
                    blnOperationSuccessful = GML.BizTalk.OperationManager.Library.OrphanOrchestrationManagement.RemoveOrchestration(orchs, dbServerName, mgntDbName);
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }
                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                outException = null;
                osm = null;
                orchs = null;
            }
        }

        private void PerformAction_OrchestrationStateManagement(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement osm = null;
            Orchestration[] oAllOrchs = null;
            Orchestration[] orchs = null;
            try
            {
                bool blnOperationSuccessful = false;
                osm = (GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement)op.Item;
                #region ---- Don't Need -----
                //    if (osm.Orchestrations != null)
                //    {
                //        Orchestration[] orchs = osm.Orchestrations;
                //        //foreach (Orchestration orch in orchs)
                //        //{
                //        //    //this.tbProgress.Text += "Found operation [" + op.ExecSequence + "] type : " + orch.GetType().Name + "." + orch.Status + "........";
                //        //    try
                //        //    {
                //        //        blnOperationSuccessful = Library.OrchestrationStateManagement.UpdateOrchestration(orch, dbServerName, mgntDbName);
                //        //    }
                //        //    catch (Exception exception)
                //        //    {
                //        //        blnOperationSuccessful = false;
                //        //        outException = exception;
                //        //    }
                //        //    //this.tbProgress.Text += "Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine;
                //        //    if (!blnOperationSuccessful && outException != null)
                //        //    {
                //        //        //this.tbProgress.Text += outException.Message + System.Environment.NewLine;
                //        //        //this.tbProgress.Text += outException.StackTrace + System.Environment.NewLine;
                //        //    }
                //        //}
                //        //this.tbProgress.Text += "Found operation [" + op.ExecSequence + "] type ........";
                //        System.Diagnostics.Debug.WriteLine("Found operation [" + op.ExecSequence + "] type ........");
                //        try
                //            {
                //                blnOperationSuccessful = Library.OrchestrationStateManagement.UpdateOrchestrations(orchs, dbServerName, mgntDbName);
                //            }
                //            catch (Exception exception)
                //            {
                //                blnOperationSuccessful = false;
                //                outException = exception;
                //            }
                //            //this.tbProgress.Text += "Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine;
                //            System.Diagnostics.Debug.WriteLine("Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine);
                //            if (!blnOperationSuccessful && outException != null)
                //            {
                //                //this.tbProgress.Text += outException.Message + System.Environment.NewLine;
                //                //this.tbProgress.Text += outException.StackTrace + System.Environment.NewLine;
                //            }
                //    }
                //    if (osm.UnenlistExclusions != null)
                //    {
                //        Orchestration[] orchs = osm.UnenlistExclusions;
                //        //this.tbProgress.Text += "Found operation [" + op.ExecSequence + "] type : " + orchs[0].GetType().Name + ".UnenlistExclusions........";
                //        System.Diagnostics.Debug.WriteLine("Found operation [" + op.ExecSequence + "] type : " + orchs[0].GetType().Name + ".UnenlistExclusions........");
                //        try
                //        {
                //            blnOperationSuccessful = Library.OrchestrationStateManagement.UpdateOrchestrations(
                //              Library.OrchestrationStateManagement.GetToBeUnenlistedList(orchs, dbServerName, mgntDbName),
                //              dbServerName, mgntDbName);

                //        }
                //        catch (Exception exception)
                //        {
                //            blnOperationSuccessful = false;
                //            outException = exception;
                //        }
                //        //this.tbProgress.Text += "Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine;
                //        System.Diagnostics.Debug.WriteLine("Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine);
                //        if (!blnOperationSuccessful && outException != null)
                //        {
                //            //this.tbProgress.Text += outException.Message + System.Environment.NewLine;
                //            //this.tbProgress.Text += outException.StackTrace + System.Environment.NewLine;
                //        }
                //    }
                //    //this.tbProgress.Text += "|" + System.Environment.NewLine;
                //    //this.tbProgress.Text += "--------------------------------------------------------------------------------------------" + System.Environment.NewLine;
                //}
                #endregion
                if (osm.Orchestrations != null)
                {

                    orchs = osm.Orchestrations;
                    #region ---- Don't Need -----
                    //foreach (Orchestration orch in orchs)
                    //{
                    //    //this.tbProgress.Text += "Found operation [" + op.ExecSequence + "] type : " + orch.GetType().Name + "." + orch.Status + "........";
                    //    try
                    //    {
                    //        blnOperationSuccessful = Library.OrchestrationStateManagement.UpdateOrchestration(orch, dbServerName, mgntDbName);
                    //    }
                    //    catch (Exception exception)
                    //    {
                    //        blnOperationSuccessful = false;
                    //        outException = exception;
                    //    }
                    //    //this.tbProgress.Text += "Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine;
                    //    if (!blnOperationSuccessful && outException != null)
                    //    {
                    //        //this.tbProgress.Text += outException.Message + System.Environment.NewLine;
                    //        //this.tbProgress.Text += outException.StackTrace + System.Environment.NewLine;
                    //    }
                    //}
                    #endregion
                    LogHelper(GetFormattedHeader("Found operation [" + op.ExecSequence + "] Orchestration State Management"), Logger.ServerityLevel.INFO, TextType.HEADER);
                    if (osm.UnenlistExclusions != null)
                    {
                        #region --- Don't Need ---
                        //System.Diagnostics.Debug.WriteLine("Starting to combine orchestrations..");
                        //LogHelper( "Starting to combine orchestrations..", Logger.ServerityLevel.INFO);
                        //Orchestration[] orchs2 = osm.UnenlistExclusions;
                        //oAllOrchs = (Orchestration[])ConcatenateArrays(orchs, Library.OrchestrationStateManagement.GetToBeUnenlistedList(orchs2, dbServerName, mgntDbName));
                        //System.Diagnostics.Debug.WriteLine("Done combining orchestrations..");
                        //LogHelper( "Done combining orchestrations..", Logger.ServerityLevel.INFO);

                        //Logger.doLog(
                        //    Guid.NewGuid().ToString(),
                        //    "=================================================================================="
                        //    + System.Environment.NewLine
                        //    + "Final Orchestration State List: "
                        //    + System.Environment.NewLine,
                        //    Logger.ServerityLevel.INFO);
                        //foreach (Orchestration orch in orchs2)
                        //{
                        //    Logger.doLog(
                        //        Guid.NewGuid().ToString(),
                        //        " ===> "
                        //        + "(" + orch.Status + ") ==> "
                        //        + orch.Fullname
                        //        + System.Environment.NewLine,
                        //        Logger.ServerityLevel.INFO);
                        //}

                        #endregion
                        oAllOrchs = (Orchestration[])ConcatenateArrays(orchs);
                    }
                    else
                    {
                        oAllOrchs = (Orchestration[])ConcatenateArrays(orchs);
                    }
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("Starting to update orchestrations status..");
                        LogHelper("Starting to update orchestrations status..", Logger.ServerityLevel.INFO, TextType.BODY);
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.OrchestrationStateManagement.UpdateOrchestrations(oAllOrchs, dbServerName, mgntDbName);
                        System.Diagnostics.Debug.WriteLine("Done updating orchestrations status..");
                        LogHelper("Done updating orchestrations status..", Logger.ServerityLevel.INFO, TextType.BODY);
                    }
                    catch (Exception exception)
                    {
                        blnOperationSuccessful = false;
                        outException = exception;
                    }
                    LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                    if (!blnOperationSuccessful && outException != null)
                    {
                        LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                        LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                    }
                    if (!blnOperationSuccessful)
                    {
                        _FailedOperationCount++;

                    }
                    else
                    {
                        _SuccessfulOperationCount++;
                    }
                }
                #region --- Don't Need ---
                //if (osm.UnenlistExclusions != null && osm.Orchestrations == null)
                //{
                //    Orchestration[] orchs = osm.UnenlistExclusions;
                //    //this.tbProgress.Text += "Found operation [" + op.ExecSequence + "] type : " + orchs[0].GetType().Name + ".UnenlistExclusions........";
                //    System.Diagnostics.Debug.WriteLine("Found operation [" + op.ExecSequence + "] type : " + orchs[0].GetType().Name + ".UnenlistExclusions........");
                //    LogHelper( "Found operation [" + op.ExecSequence + "] type : " + orchs[0].GetType().Name + ".UnenlistExclusions........", Logger.ServerityLevel.INFO);
                //    try
                //    {
                //        blnOperationSuccessful = Library.OrchestrationStateManagement.UpdateOrchestrations(
                //          Library.OrchestrationStateManagement.GetToBeUnenlistedList(orchs, dbServerName, mgntDbName),
                //          dbServerName, mgntDbName);

                //    }
                //    catch (Exception exception)
                //    {
                //        blnOperationSuccessful = false;
                //        outException = exception;
                //    }
                //    //this.tbProgress.Text += "Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine;
                //    System.Diagnostics.Debug.WriteLine("Operation " + (blnOperationSuccessful ? "successful" : "failed") + System.Environment.NewLine);
                //    LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL));
                //    if (!blnOperationSuccessful && outException != null)
                //    {
                //        //this.tbProgress.Text += outException.Message + System.Environment.NewLine;
                //        //this.tbProgress.Text += outException.StackTrace + System.Environment.NewLine;
                //        LogHelper( outException.Message, Logger.ServerityLevel.ERROR);
                //        LogHelper( outException.StackTrace, Logger.ServerityLevel.ERROR);
                //    }
                //}

                #endregion                //this.tbProgress.Text += "|" + System.Environment.NewLine;

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                outException = null;
                osm = null;
                oAllOrchs = null;
                orchs = null;
            }
        }

        private void PerformAction_RuleSetDeployment(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            bool blnOperationSuccessful = false;
            GML.BizTalk.OperationManager.MSBTSOperations.RuleSetDeployment oRSDeploy = (GML.BizTalk.OperationManager.MSBTSOperations.RuleSetDeployment)op.Item;
            if (oRSDeploy.BtsRuleSet != null)
            {
                foreach (BtsRuleSet opr in oRSDeploy.BtsRuleSet)
                {
                    LogHelper(GetFormattedHeader("Found operation [" + op.ExecSequence + "] type : " + oRSDeploy.GetType().Name + ".PublishedRule"), Logger.ServerityLevel.INFO, TextType.HEADER);
                    try
                    {
                        blnOperationSuccessful = GML.BizTalk.OperationManager.Library.RuleSetDeployment.Exec(opr.Action, opr.RuleName, new Nullable<int>(opr.MajorVersion), new Nullable<int>(opr.MinorVersion));

                    }
                    catch (Exception exception)
                    {
                        blnOperationSuccessful = false;
                        outException = exception;
                    }
                    LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                    if (!blnOperationSuccessful && outException != null)
                    {
                        LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                        LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                    }
                    if (!blnOperationSuccessful)
                    {
                        _FailedOperationCount++;

                    }
                    else
                    {
                        _SuccessfulOperationCount++;
                    }
                }
            }
            else if (oRSDeploy.RulesFromFile != null)
            {
                LogHelper(GetFormattedHeader("Found operation [" + op.ExecSequence + "] type : " + oRSDeploy.GetType().Name + ".RulesFromFile"), Logger.ServerityLevel.INFO, TextType.HEADER);
                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation has not been implemented yet.", Logger.ServerityLevel.INFO, TextType.BODY);
                _SkippedOperationCount++;
            }
            //LogHelper( "--------------------------------------------------------------------------------------------", Logger.ServerityLevel.INFO);
        }

        private void PerformAction_MSBTS_Orchestration(Operation op, string sEnvID, string dbServerName, string mgntDbName)
        {
            Exception outException = null;
            bool blnOperationSuccessful = false;
            List<ManagementBaseObject> outParam = new List<ManagementBaseObject>();
            List<ManagementBaseObject> OutputParams = new List<ManagementBaseObject>();

            GML.BizTalk.OperationManager.MSBTSOperations.MSBTS_Orchestration orch = (GML.BizTalk.OperationManager.MSBTSOperations.MSBTS_Orchestration)op.Item;
            if (orch.InvokeMethod.Equals(GML.BizTalk.OperationManager.Library.OrchestrationMethods.Enlist.ToString()))
            //&& op.ExecSequence == iLoopCount)
            {
                LogHelper(GetFormattedHeader("Found operation [" + op.ExecSequence + "] type : " + orch.GetType().Name + "." + orch.InvokeMethod), Logger.ServerityLevel.INFO, TextType.HEADER);
                try
                {
                    blnOperationSuccessful = GML.BizTalk.OperationManager.Library.MSBTS_Orchestration.Enlist(orch, ref outParam, ref outException);
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }
                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }
            }
            if (orch.InvokeMethod.Equals(GML.BizTalk.OperationManager.Library.OrchestrationMethods.Unenlist.ToString()))
            //&& op.ExecSequence == iLoopCount)
            {
                LogHelper("Found operation [" + op.ExecSequence + "] type : " + orch.GetType().Name + "." + orch.InvokeMethod + "........", Logger.ServerityLevel.INFO, TextType.HEADER);
                try
                {
                    blnOperationSuccessful = GML.BizTalk.OperationManager.Library.MSBTS_Orchestration.Unenlist(orch, ref outParam, ref outException);
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }
                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }
            }
            if (orch.InvokeMethod.Equals(GML.BizTalk.OperationManager.Library.OrchestrationMethods.Start.ToString()))
            //&& op.ExecSequence == iLoopCount)
            {
                LogHelper("Found operation [" + op.ExecSequence + "] type : " + orch.GetType().Name + "." + orch.InvokeMethod + "........", Logger.ServerityLevel.INFO, TextType.HEADER);
                try
                {
                    blnOperationSuccessful = GML.BizTalk.OperationManager.Library.MSBTS_Orchestration.Start(orch, ref outParam, ref outException);
                }
                catch (Exception exception)
                {
                    blnOperationSuccessful = false;
                    outException = exception;
                }
                LogHelper(System.Environment.NewLine + ">>>>>>>> Operation " + (blnOperationSuccessful ? "SUCCESSFUL" : "FAILED"), (blnOperationSuccessful ? Logger.ServerityLevel.INFO : Logger.ServerityLevel.FATAL), TextType.BODY);
                if (!blnOperationSuccessful && outException != null)
                {
                    LogHelper(outException.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                    LogHelper(outException.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                }
                if (!blnOperationSuccessful)
                {
                    _FailedOperationCount++;

                }
                else
                {
                    _SuccessfulOperationCount++;
                }
            }
        }

        private void btnPerformAction_Click(object sender, EventArgs e)
        {
            string dbServerName = string.Empty;
            string mgntDbName = string.Empty;
            string sEnvID = string.Empty;
            bool IsLastDeployment = false;
            try
            {
                LogHelper(GetFormattedHeader("Configuration started @ " + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")), Logger.ServerityLevel.INFO, TextType.HEADER);
                if (this.cbEnvInfo.Items != null && this.cbEnvInfo.Items.Count > 0 && envInfos != null)
                {
                    foreach (GML.BizTalk.OperationManager.MSBTSOperations.Environment env in envInfos)
                    {
                        if (env.EnvID.Equals(((ComboBoxItem)this.cbEnvInfo.SelectedItem).Content.ToString()))
                        {
                            dbServerName = env.BtsDbServerName;
                            mgntDbName = env.BtsManagmentDbName;
                            break;
                        }
                    }
                    sEnvID = ((ComboBoxItem)this.cbEnvInfo.SelectedItem).Content.ToString();
                    IsLastDeployment = ((ComboBoxItem)this.cb_lastBTSDeployment.SelectedItem).Content.ToString().ToUpper().Equals("YES");
                }
                _PerformAction thread = new _PerformAction(PerformAction);
                thread.BeginInvoke(this.oOps, this.envInfos, dbServerName, mgntDbName, sEnvID, IsLastDeployment, null, null);

                this.btn_openFile.IsEnabled = false;
                this.tb_fileName.IsEnabled = false;
                this.cbEnvInfo.IsEnabled = false;
                this.cb_lastBTSDeployment.IsEnabled = false;
                this.btnPerformAction.IsEnabled = false;
            }
            catch (Exception ex)
            {
                LogHelper(ex.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                LogHelper(ex.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
                SummarizeOperations();
                this.btn_openFile.IsEnabled = true;
                this.tb_fileName.IsEnabled = true;
                this.cbEnvInfo.IsEnabled = true;
                this.cb_lastBTSDeployment.IsEnabled = true;
                this.btnPerformAction.IsEnabled = true;
            }
        }

        private delegate void _PerformAction(GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations oOps, GML.BizTalk.OperationManager.MSBTSOperations.Environment[] envInfos, string dbServerName, string mgntDbName, string sEnvID, bool IsLastDeployment);
        private void PerformAction(GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations oOps, GML.BizTalk.OperationManager.MSBTSOperations.Environment[] envInfos, string dbServerName, string mgntDbName, string sEnvID, bool IsLastDeployment)
        {
            try
            {
                _TotalOperationCount = oOps.Operation.Length;


                int iLoopCount = 0;
                while (iLoopCount < oOps.Operation.Length)
                {
                    foreach (Operation op in oOps.Operation)
                    {
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocations))
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_ReceiveLocations(op, sEnvID, dbServerName, mgntDbName);
                            //if (IsLastDeployment)
                            //{
                            //    this.PerformAction_ReceiveLocations(op, sEnvID, dbServerName, mgntDbName);
                            //}
                            //else
                            //{
                            //    LogHelper(
                            //       GetFormattedHeader("Skipping operation [" + op.ExecSequence + "] for ReceiveLocations because this is not the last bizTalk deployment"),
                            //        Logger.ServerityLevel.INFO, TextType.HEADER
                            //        );
                            //    _SkippedOperationCount++;
                            //}
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.SendPorts))
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_SendPorts(op, sEnvID, dbServerName, mgntDbName);
                            //if (IsLastDeployment)
                            //{
                            //    this.PerformAction_SendPorts(op, sEnvID, dbServerName, mgntDbName);
                            //}
                            //else
                            //{
                            //    LogHelper(
                            //        GetFormattedHeader("Skipping operation [" + op.ExecSequence + "] for SendPorts because this is not the last bizTalk deployment"),
                            //        Logger.ServerityLevel.INFO, TextType.HEADER
                            //        );
                            //    _SkippedOperationCount++;
                            //}
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroups))
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_SendPortGroups(op, sEnvID, dbServerName, mgntDbName);
                            //if (IsLastDeployment)
                            //{
                            //    this.PerformAction_SendPorts(op, sEnvID, dbServerName, mgntDbName);
                            //}
                            //else
                            //{
                            //    LogHelper(
                            //        GetFormattedHeader("Skipping operation [" + op.ExecSequence + "] for SendPorts because this is not the last bizTalk deployment"),
                            //        Logger.ServerityLevel.INFO, TextType.HEADER
                            //        );
                            //    _SkippedOperationCount++;
                            //}
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.HostInstances))
                                && op.ExecSequence == iLoopCount)
                        {
                            if (IsLastDeployment)
                            {
                                this.PerformAction_HostInstances(op, sEnvID, dbServerName, mgntDbName);
                            }
                            else
                            {
                                LogHelper(
                                    GetFormattedHeader("Skipping operation [" + op.ExecSequence + "] for host instance(s) because this is not the last bizTalk deployment"),
                                    Logger.ServerityLevel.INFO, TextType.HEADER
                                    );
                                _SkippedOperationCount++;
                            }
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstances))
                                && op.ExecSequence == iLoopCount)
                        {
                            if (IsLastDeployment)
                            {
                                this.PerformAction_ServiceInstances(op, sEnvID, dbServerName, mgntDbName);
                            }
                            else
                            {
                                LogHelper(
                                    GetFormattedHeader("Skipping operation [" + op.ExecSequence + "] for ServiceInstances because this is not the last bizTalk deployment"),
                                    Logger.ServerityLevel.INFO, TextType.HEADER
                                    );
                                _SkippedOperationCount++;
                            }
                        }
                        if (op.Item.GetType().Name.Equals(GML.BizTalk.OperationManager.Library.OperationsType.BindingInfo.ToString())
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_BindingInfo(op, sEnvID, dbServerName, mgntDbName);
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.Library.OrphanOrchestrationManagement))
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_OrphanOrchestrationManagement(op, sEnvID, dbServerName, mgntDbName);
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement))
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_OrchestrationStateManagement(op, sEnvID, dbServerName, mgntDbName);
                            //if (IsLastDeployment)
                            //{
                            //    this.PerformAction_OrchestrationStateManagement(op, sEnvID, dbServerName, mgntDbName);
                            //}
                            //else
                            //{
                            //    LogHelper(
                            //        GetFormattedHeader("Skipping operation [" + op.ExecSequence + "] for OrchestrationStateManagement because this is not the last bizTalk deployment"),
                            //        Logger.ServerityLevel.INFO, TextType.HEADER
                            //        );
                            //    _SkippedOperationCount++;
                            //}
                        }
                        if (op.Item.GetType().Equals(typeof(GML.BizTalk.OperationManager.MSBTSOperations.RuleSetDeployment))
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_RuleSetDeployment(op, sEnvID, dbServerName, mgntDbName);
                        }
                        if (op.Item.GetType().Name.Equals(GML.BizTalk.OperationManager.Library.OperationsType.MSBTS_HostInstance.ToString())
                                && op.ExecSequence == iLoopCount)
                        {
                            /*
                                GetState - Retrieves the state of the given instance of the BizTalk host. 
                                Install - Installs a service for the given instance of the BizTalk host. 
                                Start - Starts the given instance of the BizTalk host. 
                                Stop - Stops the given instance of the BizTalk host. 
                                Uninstall - Uninstalls a service for the given instance of the BizTalk host. 
                             * */
                        }
                        if (op.Item.GetType().Name.Equals(GML.BizTalk.OperationManager.Library.OperationsType.MSBTS_Host.ToString())
                                && op.ExecSequence == iLoopCount)
                        {
                            /*
                            Start - Starts all BizTalk Host instances in the BizTalk group for the given BizTalk Host. 
                            Stop - Stops all BizTalk Host instances in the BizTalk group for the given BizTalk Host. 
                             * */

                        }
                        if (op.Item.GetType().Name.Equals(GML.BizTalk.OperationManager.Library.OperationsType.MSBTS_Orchestration.ToString())
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_MSBTS_Orchestration(op, sEnvID, dbServerName, mgntDbName);

                        }
                        if (op.Item.GetType().Name.Equals(GML.BizTalk.OperationManager.Library.OperationsType.GACVerification.ToString())
                                && op.ExecSequence == iLoopCount)
                        {
                            this.PerformAction_GACListCompare(op, envInfos, sEnvID, dbServerName, mgntDbName);

                        }

                    }
                    iLoopCount++;
                }

            }
            catch (Exception ex)
            {
                LogHelper(ex.Message, Logger.ServerityLevel.ERROR, TextType.BODY);
                LogHelper(ex.StackTrace, Logger.ServerityLevel.ERROR, TextType.BODY);
            }

            SummarizeOperations();
        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private static Array ConcatenateArrays(params Array[] arrays)
        {
            if (arrays == null)
            {
                throw new ArgumentNullException("arrays");
            }
            if (arrays.Length == 0)
            {
                throw new ArgumentException("No arrays specified");
            }

            Type type = arrays[0].GetType().GetElementType();
            int totalLength = arrays[0].Length;
            for (int i = 1; i < arrays.Length; i++)
            {
                if (arrays[i].GetType().GetElementType() != type)
                {
                    throw new ArgumentException
                    ("Arrays must all be of the same type");
                }
                totalLength += arrays[i].Length;
            }

            Array ret = Array.CreateInstance(type, totalLength);
            int index = 0;
            foreach (Array array in arrays)
            {
                Array.Copy(array, 0, ret, index, array.Length);
                index += array.Length;
            }
            return ret;
        }

        private void SummarizeOperations()
        {
            LogHelper(GetFormattedHeader("Configuration finished @ " + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")), Logger.ServerityLevel.INFO, TextType.HEADER);
            string summary =
                "============================================================================" + System.Environment.NewLine +
                "|| SUMMARY ||" + System.Environment.NewLine +
                "============================================================================" + System.Environment.NewLine +
                "|| Total Operations Count = " + _TotalOperationCount + System.Environment.NewLine +
                "|| Successful Operations Count = " + _SuccessfulOperationCount + System.Environment.NewLine +
                "|| Skipped Operations Count = " + _SkippedOperationCount + System.Environment.NewLine +
                "|| Failed Operations Count = " + _FailedOperationCount + System.Environment.NewLine +
                "============================================================================" + System.Environment.NewLine;
            
            Logger.ServerityLevel severity = Logger.ServerityLevel.INFO;
            if(_FailedOperationCount>0) severity = Logger.ServerityLevel.ERROR;
            else if (_SkippedOperationCount>0) severity=Logger.ServerityLevel.WARN;
            else severity = Logger.ServerityLevel.INFO;

            LogHelper(summary, severity, TextType.HEADER);
        }

    }
}
